import { ConfigProvider, Divider, Empty, Form, Pagination, Table } from "antd";
import SForm from "../form";
import SButton from "../button";
import { useEffect, useRef, useState } from "react";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import styles from "./index.module.css";
import { isEmpty } from "wsp-toolkit";

/**
 *
 * @param props {{
 *   children?: ReactNode;
 *   columns: [];
 *   dataSource: [];
 *   bordered: boolean;
 *   formItems?: FormItem[];
 *   onChange?: (page: number) => void;
 *   page?: number;
 *   parentRef?: any;
 *   residual?: number;
 *   scrollX?: number;
 *   form?: FormInstance<any>;
 *   total?: number;
 *   loading?: boolean;
 *   onSearch?: () => void;
 *   onReset?: () => void;
 * }}
 * @returns {JSX.Element}
 */
export default function (props) {
  const {
    children,
    columns,
    dataSource,
    bordered = true,
    formItems = [],
    onChange,
    onShowSizeChange,
    residual = 0,
    form,
    scrollX,
    total = 0,
    loading,
    onSearch,
    onReset,
    paginationConfig = {},
    ...otherProps
  } = props;
  const [_form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const parentRef = useRef(null);
  const headerRef = useRef(null);
  const [parentHeight, setParentHeight] = useState(0);
  const [_formItems, setFormItems] = useState(formItems.slice(0, 2))
  const finalForm = form || _form;
  const isEmptyData = isEmpty(dataSource);

  const pagination = {
    current: 1,
    pageSize: 30,
    pageSizeOptions:[10, 30, 50, 100],
    // hideOnSinglePage: true,
    showSizeChanger: true,
    showQuickJumper: true,
    size: "small",
    total,
    showTotal: (total, range) => {
      return `共${total}条`;
    },
    onChange: (page, pageSize) => {
      onChange?.(page, pageSize);
    },
    onShowSizeChange:(current, size)=>{
      onShowSizeChange?.(current, size)
    },
    ...paginationConfig
  };

  const needShowOpen = formItems.length > 2;

  const handleOpenClick = () => {
    const isOpen = !open
    setOpen(isOpen)
    setFormItems(isOpen ? [...formItems] : formItems.slice(0, 2))
  }

  function calcSize() {
    const tableRect = parentRef.current.getBoundingClientRect();
    const headerRect = headerRef.current.getBoundingClientRect();
    setParentHeight(tableRect.bottom - headerRect.bottom - residual);
  }

  useEffect(() => {
    parentRef.current.addEventListener("resize", calcSize);
    calcSize();

    return () => {
      if (parentRef.current) {
        parentRef.current.removeEventListener("resize", calcSize);
      }
    };
  }, []);

  return (
    <div
      style={{
        overflow: "hidden",
        height: "100%",
        width: "100%",
        display: "flex",
        flexDirection: "column",
      }}
    >
      {formItems.length > 0 && (
        <div>
          <SForm
            formItems={_formItems}
            form={finalForm}
          >
            <SButton
              type={"primary"}
              style={{ marginRight: 16 }}
              onClick={onSearch}
            >
              搜索
            </SButton>
            <SButton onClick={onReset}>重置</SButton>
            {needShowOpen && (
              <SButton
                type={"link"}
                icon={
                  <UpOutlined
                    className={open ? "" : styles.downIcon}
                    style={{ transition: "all .3s" }}
                  />
                }
                onClick={handleOpenClick}
              >
                {open ? "收起" : "展开"}
              </SButton>
            )}
          </SForm>
          <Divider style={{ marginTop: 0, marginBottom: 16 }} />
        </div>
      )}
      {children}
      <div style={{ flexGrow: 0.9, overflow:"scroll" }} ref={parentRef}>
        <ConfigProvider renderEmpty={() => <Empty style={{width: "100%", height:"100%"}}/>}>
          <Table
            {...otherProps}
            loading={loading}
            onHeaderRow={() => {
              return {
                ref: headerRef,
              };
            }}
            bordered={bordered}
            columns={columns}
            dataSource={dataSource}
            size={"small"}
            pagination={false}
            scroll={{
              x: scrollX,
              y: isEmptyData ? undefined : parentHeight,
            }}
          />
        </ConfigProvider>
      </div>
      {!isEmptyData && (
        <div
          style={{
            marginTop: "16px",
            display: "flex",
            justifyContent: "flex-end",
            alignItems: "center",
          }}
        >
          <Pagination rootClassName={styles.pagination} {...pagination} />
        </div>
      )}
    </div>
  );
}
